module.exports = function ($timeout, toaster, $resource) {
    return {
        restrict: 'E',
        // require: 'ngModel',
        template: require('../views/priceCalendar.html'),
        scope: {
            /**
             * $scope.data = [
                    {'d' : '2017-03-03', 'market_price_display' : '132' [, key: value]},
                    {}
                ];
             */
            data: '=',              //日历数据
            /**
             * $scope.showattrarr = [
                    {
                        key: 'market_price_display',//字段
                        position: 'left',           //单元格显示位置
                        before: '<font color=red >市场价格: ¥</font>'//单元格数据label
                    },
                    {}
                ];
             */
            showattrarr: '=',       //数据显示规则
            /**
             * $scope.options = {
                    btn_flag: true,//是否显示按钮
                    btn_left: 'String',//左按钮字样
                    btn_right: 'String',//右按钮字样
                    leftClick: function () {//左按钮函数
                    },
                    rightClick: function(){//右按钮函数
                    },
                    click: function (item) {//每天的点击事件
                    },
                    state: 'String',     //背景灰判断字段
                    checkbox: boolean     //是否有checkbox
                }
             */
            options: '=',           //日历样式丶函数等配置
            date: '@'               //当前显示月份所包含的任意一天
        },
        link: function (scope, $element, $attrs, ngModel) {
			/**
			 * 下方是初始化方法
			 */
            scope.count = 1;
            scope.refresh = function () {
                scope.count += 1;
                scope.dataobj = {};
                if (angular.isDefined(scope.data) && angular.isArray(scope.data)) {
                    for (var i = 0; i < scope.data.length; i++) {
                        var tmp = scope.data[i];
                        scope.dataobj[tmp.d] = tmp;
                    }
                }

                var showattrarr = [];
                if (angular.isDefined(scope.showattrarr) && angular.isArray(scope.showattrarr)) {
                    showattrarr = scope.showattrarr;
                }

                scope.weekarr = ["<font color=red>日</font>", "一", "二", "三", "四", "五", "<font color=red>六</font>"];
                scope.weekDay = [
                    { day: '周日', check: false },
                    { day: '周一', check: false },
                    { day: '周二', check: false },
                    { day: '周三', check: false },
                    { day: '周四', check: false },
                    { day: '周五', check: false },
                    { day: '周六', check: false }
                ]

                var obj = {};
                var date = scope.date ? new Date(scope.date) : new Date();
                var year = date.getFullYear();
                var month = date.getMonth();

                scope.obj = makedata(year, month, scope.dataobj, showattrarr);

                scope.pre = function () {
                    clearData();
                    var dd = getYM(scope.obj.y, scope.obj.m, -1);
                    scope.obj = makedata(dd.y, dd.m, scope.dataobj, showattrarr);
                };

                scope.back = function () {
                    clearData();
                    var dd = getYM(scope.obj.y, scope.obj.m, 1);
                    scope.obj = makedata(dd.y, dd.m, scope.dataobj, showattrarr);
                };

                function makedata(year, month, dataobj, showattrarr) {
                    var montharray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
                    var obj = {
                        'y': year,
                        'm': month,
                        'data': [],
                    };
                    if ((obj.m === 1) && (obj.y % 4 === 0)
                        && ((obj.y % 100 !== 0) || (obj.y % 400 === 0))) {
                        montharray[1] = 29;
                    }
                    //1号
                    var firstdate = new Date(obj.y, obj.m, 1);
                    //最后一号
                    var lastdate = new Date(obj.y, obj.m, montharray[obj.m]);

                    //1号星期几
                    var fxingqi = firstdate.getDay();
                    //最后一号星期几
                    var lxingqi = lastdate.getDay();

                    var dataarr = [];
                    //日期之前的空位
                    for (var f = 0; f < fxingqi; f++) {
                        var dayobj = {
                            'label': '',
                            'd': '0',
                        };
                        dataarr.push(dayobj);
                    }

                    //组装当月日期及数据
                    for (var j = 0; j < montharray[obj.m]; j++) {
                        var dayobj = {
                            'label': j + 1,
                            'd': obj.y + '-',
                            'labelarr': [],	//具体显示的信息
                            'selected': false,
                            'state': '0'
                        };

                        /*****************组装dayobj.d   日期 **********************/
                        if (obj.m < 9) {
                            dayobj.d += '0' + (obj.m + 1) + '-';
                        } else {
                            dayobj.d += obj.m + 1 + '-';
                        }

                        if (j < 9) {
                            dayobj.d += '0' + (j + 1);
                        } else {
                            dayobj.d += (j + 1);
                        }
                        /****************组装dayobj.d   完毕 **********************/

                        //今天之前  及 没有数据的  不要checkbox
                        if (dayobj.d < date2str(new Date()) || (dataobj[dayobj.d] === undefined)) {
                            delete dayobj.selected;
                        }

                        //没有数据的  不要背景色
                        if ((dataobj[dayobj.d] === undefined)) {
                            delete dayobj.state;
                        } else {
                            dayobj.state = dataobj[dayobj.d][scope.options.state];
                        }

                        //有数据要显示。 组装dayobj.labelarr
                        var show = dataobj[dayobj.d];
                        if (angular.isDefined(dataobj[dayobj.d])) {
                            for (var x = 0; x < showattrarr.length; x++) {
                                var xx = showattrarr[x];
                                var ooo = {
                                    'show': ((xx.before && show[xx.key]) ? xx.before : '') + (show[xx.key] ? show[xx.key] : '') + ((xx.after && show[xx.key]) ? xx.after : ''),
                                    'position': xx.position
                                };
                                dayobj.labelarr.push(ooo);
                                dayobj['data'] = show;
                            }
                        }
                        dataarr.push(dayobj);
                    }
                    //日期之后的空位
                    for (var l = lxingqi; l < 6; l++) {
                        var dayobj = {
                            'label': '',
                            'd': '0',
                        };
                        dataarr.push(dayobj);
                    }

                    for (var i = 0; i < dataarr.length; i++) {
                        //每七个重新组装一个数组。
                        var x = i % 7;
                        if (x === 0) {
                            obj.data.push(new Array());
                        }
                        obj.data[obj.data.length - 1].push(dataarr[i]);
                    }
                    return obj;
                }

                //step 负数，之前几个月，-1：表示之前一个月
                //     正数，之后几个月，1 ：表示之后一个月
                function getYM(y, m, step) {
                    var yy = y;
                    var mm = m;

                    if (mm + step < 0) {
                        yy -= 1;
                        mm = 12 + mm + step;
                    } else if (mm + step > 11) {
                        yy += 1;
                        mm = mm + step - 12;
                    } else {
                        mm += step;
                    }

                    return {
                        'y': yy,
                        'm': mm,
                    }
                }

                function clearData() {
                    scope.weekDay = [
                        { day: '周日', check: false },
                        { day: '周一', check: false },
                        { day: '周二', check: false },
                        { day: '周三', check: false },
                        { day: '周四', check: false },
                        { day: '周五', check: false },
                        { day: '周六', check: false }
                    ];
                }

                //选中一周中的某一天, 相应日期背景颜色变化
                scope.$watch('weekDay', function (newValue) {
                    for (var index = 0; index < scope.weekDay.length; index++) {
                        var flag = scope.weekDay[index].check == true;
                        for (var i = 0; i < scope.obj.data.length; i++) {
                            var element = scope.obj.data[i];
                            if (element[index].selected !== undefined) {
                                element[index].selected = flag;
                            }
                        }
                    }
                }, true);




            }

            function date2str(objDate) {
                if (angular.isDate(objDate)) {
                    var y = objDate.getFullYear();
                    var m = objDate.getMonth() + 1;
                    var d = objDate.getDate();
                    m = m < 10 ? '0' + m : m;
                    d = d < 10 ? '0' + d : d;
                    return y + '-' + m + '-' + d;
                }
                else {
                    return '错误格式';
                }
            }

            // scope.count = 0;
            scope.$watch('data', function (newValue) {
                if (!scope.options.is_stop_refresh || scope.count < 3) {
                    scope.refresh();
                }
            }, true);

            scope.checkDate = function (date, event) {
                if (date.d < date2str(new Date())) {
                    toaster.info({ title: date.d, body: '日期不能小于当前日期' });
                }
                event.stopPropagation();
            }

        }
    };
}